package com.ywu.boot.interceptor.impl;

import com.ywu.boot.config.BootConfigAppConfig;
import com.ywu.boot.context.YwuContext;
import com.ywu.boot.context.YwuContextHolder;
import com.ywu.boot.exception.YwuRuntimeException;
import com.ywu.boot.interceptor.ContextBuilderInterface;
import com.ywu.common.gson.GsonUtils;
import com.ywu.common.utils.AesUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName YwuContextHandler
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/6/8 23:07
 * @Version 1.0
 **/
@Component
@Slf4j
@Order(5)
public class YwuContextBuilder implements ContextBuilderInterface {
    private static final String YWU_CONTEXT_HEADER = "YWU-CONTEXT-HEADER";

    @Autowired
    private BootConfigAppConfig bootConfigAppConfig;

    @Override
    public void buildContext(HttpServletRequest request, HttpServletResponse response) {
        String ywuContextInfo = request.getHeader(YWU_CONTEXT_HEADER);
        String decryptKey;
        try {
            if (StringUtils.isEmpty(ywuContextInfo)) {
                log.warn("YwuContextBuilder buildContext ywuContext is Empty");
                return;
            }
            decryptKey = AesUtils.decrypt(ywuContextInfo, bootConfigAppConfig.getSecretKey());
            log.debug("YwuContextBuilder decryptKey is {}", decryptKey);
            // 反序列化为对象
            YwuContext deserialize = GsonUtils.deserialize(decryptKey, YwuContext.class);
            YwuContextHolder.setCurrentContext(deserialize);
        } catch (Exception e) {
            log.error("ywuContext decrypt error {}", e.getMessage());
            throw new YwuRuntimeException(e.getMessage());
        }
    }

    @Override
    public String getBuildHeaderKey() {
        return YWU_CONTEXT_HEADER;
    }
}
